from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.database import get_db
from app.api.auth import get_current_user
from app.schemas.user import UserInDB

router = APIRouter()

# 上传资源
@router.post("/", response_model=schemas.ResourceResponse, status_code=status.HTTP_201_CREATED)
def create_resource(
    resource: schemas.ResourceCreate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    # 如果提供了关联案例ID，验证案例是否存在
    if resource.related_case_id:
        db_case = crud.case.get_case(db, case_id=resource.related_case_id)
        if not db_case:
            raise HTTPException(status_code=404, detail="Case not found")
    
    created_resource = crud.resource.create_resource(db=db, resource=resource)
    return created_resource

# 获取资源列表
@router.get("/", response_model=list[schemas.ResourceResponse])
def read_resources(
    skip: int = 0,
    limit: int = 100,
    type: str = None,
    related_case_id: int = None,
    db: Session = Depends(get_db)
):
    resources = crud.resource.get_resources(
        db, 
        skip=skip, 
        limit=limit, 
        type=type, 
        related_case_id=related_case_id
    )
    return resources

# 获取资源详情
@router.get("/{resource_id}", response_model=schemas.ResourceResponse)
def read_resource(resource_id: int, db: Session = Depends(get_db)):
    db_resource = crud.resource.get_resource(db, resource_id=resource_id)
    if db_resource is None:
        raise HTTPException(status_code=404, detail="Resource not found")
    return db_resource

# 更新资源
@router.put("/{resource_id}", response_model=schemas.ResourceResponse)
def update_resource(
    resource_id: int,
    resource: schemas.ResourceUpdate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    db_resource = crud.resource.get_resource(db, resource_id=resource_id)
    if db_resource is None:
        raise HTTPException(status_code=404, detail="Resource not found")
    
    # 如果提供了关联案例ID，验证案例是否存在
    if resource.related_case_id:
        db_case = crud.case.get_case(db, case_id=resource.related_case_id)
        if not db_case:
            raise HTTPException(status_code=404, detail="Case not found")
    
    updated_resource = crud.resource.update_resource(db, resource_id=resource_id, resource=resource)
    return updated_resource

# 删除资源
@router.delete("/{resource_id}", response_model=schemas.ResourceResponse)
def delete_resource(
    resource_id: int,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    db_resource = crud.resource.get_resource(db, resource_id=resource_id)
    if db_resource is None:
        raise HTTPException(status_code=404, detail="Resource not found")
    
    deleted_resource = crud.resource.delete_resource(db, resource_id=resource_id)
    return deleted_resource